#!/bin/bash 

CONTROL_FILE=DEBIAN/control
LIST_UKUICHROOT=~/packages_with_amd64_suffix.txt
# 获取脚本的绝对路径，考虑符号链接  
ABS_PATH=$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")  
# 提取脚本所在的目录  
SCRIPT_DIR=$(dirname "$ABS_PATH")
FINISH_ARGS_FILE="$4"
# 依赖文件路径
DEPENDS_DIR=$SCRIPT_DIR/BUILD/depends/
#已下载的依赖列表
DEPENDALREADY_ARRAY=()
#是否含有OPT路径
HAVE_OPTDIR=0
#是否含有/usr/bin路径
HAVE_USRBIN=1

check_depends() {

  # 使用grep提取Depends信息  
  local dependencies=$(grep "^Depends:" "$CONTROL_FILE" | sed 's/Depends://')
  local dependsneeddl_array=()

  # 使用逗号分隔提取的字符串，并遍历输出
  IFS=',' read -r -a depends_array <<< "$dependencies"
  for item in "${depends_array[@]}"; do
    cleaned_string="${item%% \(*>*}"  #清除包名后面的版本号
    if [[ "$cleaned_string" == "$item" ]]; then
      cleaned_string="${item%% \(*=*}" 
    fi
    if [[ "$cleaned_string" == "$item" ]]; then
      cleaned_string="${item%% \(*<*}" 
    fi
    if [[ "$cleaned_string" == "$item" ]]; then
      cleaned_string="${item%%:*}"
    fi

    # 检查是否包含 |
    if [[ "$cleaned_string" =~ "|" ]]; then
      echo "警告: '$cleaned_string' 仍然包含 '|', 未能成功清理."
      IFS='|' read -ra split_items <<< "$cleaned_string"
      for item in "${split_items[@]}"; do
        #echo "清除版本号后包名为 '$item'"
        grep -q $item: $LIST_UKUICHROOT
        if [ ! $? -eq 0 ]; then
          echo "The string '$item' was not found."
          dependsneeddl_array+=("$item")
        fi
      done
    else
      #echo "清除版本号后包名为 '$cleaned_string'"
      grep -q $cleaned_string: $LIST_UKUICHROOT
      if [ ! $? -eq 0 ]; then
        echo "The string '$cleaned_string' was not found."
        dependsneeddl_array+=("$cleaned_string")
      for needdl in "${dependsneeddl_array[@]}"; do 
        echo "depends数组中的内容 '$needdl'"
      done
      fi
    fi
  done

  if [ ${#dependsneeddl_array[@]} -eq 0 ]; then   #if dependsneeddl_array不为空
    echo "do not need download depend"
    return
  else 
    for depend in "${dependsneeddl_array[@]}"; do
      # 如果已下载则跳出本次循环，避免循环依赖  
      if_already_download $depend
      if [ $? -eq 0 ]; then
        continue
      fi
      
      if [ ! -d "./$depend" ]; then
        DEPENDALREADY_ARRAY+=("$depend")
        mkdir $depend
        cd $depend
        apt download $depend >/dev/null 2>&1 
        echo "解压依赖'$depend'"
        dpkg-deb -R *.deb . >/dev/null 2>&1
        cp -r ./usr/* $SCRIPT_DIR/BUILD/depends/
        check_depends
        cd ..
      else
        echo "'$depend'已存在"
      fi
    done
  fi

}


if_already_download () {
  depend=$1
  if [ ! ${#DEPENDALREADY_ARRAY[@]} -eq 0 ]; then  
    for element in "${DEPENDALREADY_ARRAY[@]}"; do 
      if [[ "$element" == "$depend" ]]; then  
        echo "'$element'已下载，跳出本次下载"
        return 0 
      fi  
    done 
  fi
  return 1 
}

is_lib_empty() {
  local lib_dir="$1"
  if [[ -z "$(ls -A "$lib_dir")" ]]; then
    echo 1   # 返回1表示目录为空
  else
    echo 0   # 返回0表示目录不为空   
  fi
}

is_dir_exist() {
  local dir_path="$1"
  if [ -d "$dir_path" ]; then
    echo 1   # 返回1表示目录存在
  else
    echo 0   # 返回0表示目录不存在
  fi
}

change_dirname() {
  local etc_dir_is_exist=$(is_dir_exist "./etc")
  mv ./usr/* ./app/
  if [ "$etc_dir_is_exist" -eq 1 ]; then
    mv ./etc ./app/
  fi

  if [ -d "./opt" ]; then
    HAVE_OPTDIR=1
    mv ./opt ./app/
  fi
  pwd
  if [ ! -d "./app/bin" ]; then
    HAVE_USRBIN=0
  fi
  
  if [ -d "./app/games/" ]; then
    mv $SCRIPT_DIR/BUILD/app/games $SCRIPT_DIR/BUILD/app/bin
  fi
}

filling_yml() {
  local idname=$1    
  local command=$2
  local finish_args=$(<"$3")
  local lib_is_empty=$(is_lib_empty $DEPENDS_DIR)
  local etc_dir_is_exist=$(is_dir_exist "./etc")
  local schemas_dir="./app/share/glib-2.0/schemas"
  local depends_schemas_dir="./depends/share/glib-2.0/schemas"
  local post_install="post-install:
    - glib-compile-schemas /app/share/glib-2.0/schemas
    "    

  if [ -f "./$idname.appdata.xml" ]; then
  local build_command=" 
      - cp -r ./app/* /app/
      - install -Dm644 -t /app/share/metainfo/ $idname.appdata.xml"
  else
  local build_command=" 
      - cp -r ./app/* /app/"   
  fi

  local desktop_icon_name=$(grep -oP 'Icon=\K[^;]*' "./app/share/applications/$idname.desktop" | head -n 1)
  local icon_name=$(basename "$desktop_icon_name" | sed 's/\..*$//') 
  echo "---------iconname is $icon_name-------"
  local rename_icon="rename-icon: $icon_name"
  local desktop_exec_name=$(grep -oP 'Exec=\K[^;]*' "./app/share/applications/$idname.desktop" | head -n 1)
  local exec_name=$(echo "$desktop_exec_name" | tr -d '"')
  echo "---------exec_name is $exec_name-------"

  if [ $HAVE_OPTDIR -eq 1 ] && [ $HAVE_USRBIN -eq 0 ]; then
    build_command+="
      - install -Dm755 -t /app/bin/ $command"
  fi

  #local install_icon="
  #  - install -Dm644 $icon_name -t /app/share/icons/hicolor/scalable/apps/"

  #沙箱内默认动态库地址为/app/lib,其他地址无法链接到
  if [ -d "./app/lib/x86_64-linux-gnu" ]; then
    cp -r ./app/lib/x86_64-linux-gnu/* ./app/lib/
  fi

  if [ -d "./depends/lib/x86_64-linux-gnu" ]; then
    cp -r ./depends/lib/x86_64-linux-gnu/* ./depends/lib/
  fi


# 定义YAML文件内容
yaml_content="id: $idname
runtime: top.openkylin.Platform
runtime-version: '2.0'
sdk: top.openkylin.Sdk
branch: stable
command: $command
$rename_icon
finish-args:
$finish_args
modules:
"
    # 根据lib文件夹是否为空，动态添加deps-libs模块
    if [ "$lib_is_empty" -eq 0 ]; then
        yaml_content+="  - name: deps-libs
    buildsystem: simple
    "    
    if [ -d "$depends_schemas_dir" ]; then
    yaml_content+="$post_install"
    fi

    yaml_content+="build-commands:
      - mkdir /app/lib  
      - cp -r * /app/
    sources:
      - type: dir
        path: ./depends
"
    fi 

    yaml_content+="  - name: $command
    buildsystem: simple
    "
    if [ -d "$schemas_dir" ]; then
    yaml_content+="$post_install"
    fi

    yaml_content+="build-commands:$build_command
    sources:
      - type: dir
        path: ./
"
  if [ $HAVE_OPTDIR -eq 1 ] && [ $HAVE_USRBIN -eq 0 ]; then
  yaml_content+="      - type: script
        dest-filename: $command
        commands:
         - exec /app$exec_name 
"
  fi

	# 写入YAML文件
	output_file="$idname.yml"

	# 创建并写入文件
	echo "$yaml_content" > "$output_file"

	# 检查是否成功写入
	if [ $? -eq 0 ]; then
	  echo "YAML file '$output_file' created successfully."
	else
	  echo "Error creating YAML file."
	fi

}


update_filedesktop() {
  local flatpak_id=$1
  local tmp_contents=$(ls ./app/share/applications/)
  local desktop_file_path="./app/share/applications/$tmp_contents"

  #找到./app/share/applications/app.desktop文件
  if [ -f "$desktop_file_path" ]; then
    # 使用sed命令替换Icon字段的内容  
    #sed -i 's/^Icon=.*$/Icon='$flatpak_id'/' "$desktop_file_path"  
  
    # 重命名文件  
    mv "$desktop_file_path" "./app/share/applications/$flatpak_id.desktop"  
    echo "文件已更新并重命名成功。"  
  else  
    echo "文件 $desktop_file_path 不存在。"
  fi
}

remove_depends_locale() {
  local locale_dir="./depends/share/locale"
  if [ -d "$locale_dir" ]; then
    rm -rf "$locale_dir"
    echo "删除目录 $locale_dir 成功"
  else
    echo "目录 $locale_dir 不存在"
  fi
}

add_appdate() {

  local time=$(date  +%Y-%m-%e)
  local idname=$1
  local name=$2
  local version=$3

  if [ -f "app/share/metainfo/$idname.appdata.xml" ]; then
     echo "appdata已存在"
     return
  fi
  
  # 创建appdata.xml
  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<component type=\"desktop\">
  <id>$idname</id>
  <metadata_license>CC0-1.0</metadata_license>
  <name>$name</name>
  <summary> null </summary>
  <description>
    <p>    
        $name
    </p>
  </description>
  <url type=\"homepage\">http://www.openkylin.top/</url>
  <releases>
    <release version=\"$version\" date=\"$time\"/> 
  </releases>
</component>">$idname.appdata.xml

  #cp $idname.appdata.xml app/share/metainfo/$idname.appdata.xml

}

change_filedesktop() {
  local flatpak_id=$1
  command_name=$2
  local desktop_file_path="./app/share/applications/$flatpak_id.desktop"

  #使用sed命令替换Icon字段的内容  
  sed -i 's/^Icon=.*$/Icon='$flatpak_id'/' "$desktop_file_path"
  #替换exec
  sed -i 's/^Exec=.*$/Exec='$command_name'/' "$desktop_file_path"
  #if [ $HAVE_OPTDIR -eq 1 ]; then
  #  sed -i 's|\(Exec=\).*/\([^/]*\)$|\1\2|' "$desktop_file_path"
  #fi

}



#-------------------------main---------------------------------

# 检查是否提供了参数  
#if [ "$#" -ne 5 ]; then  
#    echo "需要四个参数,第一个为.deb文件名 第二个为包id及yml文件名 第三个command"
#    exit 1  
#fi  
  
# 检查文件是否存在  
if [ ! -f "$1" ]; then  
  echo "文件 $1 不存在"  
  exit 1  
fi  
  
# 检查文件扩展名是否为.deb  
if [[ "$1" != *.deb ]]; then  
  echo "提供的文件不是一个.deb包"  
  exit 1  
fi 

# 如果编译临时目录已存在，先清除
if [ -d BUILD ]; then
  echo "BUILD路径已存在，移除"
  rm -r BUILD
fi

mkdir BUILD
mkdir BUILD/depends
mkdir BUILD/app
# 使用dpkg-deb列出.deb包的内容  
dpkg-deb -R "$1" BUILD
cd BUILD

echo "脚本所在路径：$SCRIPT_DIR"
#----------------------分析contrl文件中的depend信息-------------------

check_depends
#移除依赖包中的locale，否则会影响编译
remove_depends_locale

#-----------------------编译准备及添加appdate文件--------------------------

change_dirname
update_filedesktop $2 $3
add_appdate $2 $3 $5

#---------------------------填充yml文件-------------------------------

echo "第二个参数为'$2' 第三个参数为'$3'"
echo "第四个参数为'$FINISH_ARGS_FILE'"
filling_yml "$2" "$3" "../$FINISH_ARGS_FILE"
change_filedesktop $2 $3

#--------------------------- 开始编译---------------------------------
if [ -z "${BUILD_SWITCH_ENV}" ] || [ "${BUILD_SWITCH_ENV}" != "off" ]; then
  faltpak-builder build --force-clean --verbose --repo=repo --install --user $2.yml
fi

